package com.pan.behavioral.observer.traffic;

import com.pan.behavioral.observer.pattern.Observer;
import com.pan.behavioral.observer.pattern.Subject;
import com.pan.behavioral.observer.traffic.lane.Lane;

import java.util.*;

public class TrafficLight implements Subject<String> {


    private List<Lane> laneList = new ArrayList<>();

    public TrafficLight(){

    }


    private String lampStatus = "east-west: red; north-south: green;";
    @Override
    public void addObserver(Observer observer) {
        if (observer instanceof Lane) {
            this.laneList.add((Lane) observer);
        } else {
            throw new RuntimeException("Observer Error: Traffic Light can only manages Lane");
        }
    }
    @Override
    public void removeObserver(Observer observer) {
        if (!(observer instanceof Lane)){
            throw new RuntimeException("Observer Error: Traffic Light can only manages Lane");
        }
        Lane lane = (Lane) observer;
        Iterator<Lane> iterator = laneList.iterator();
        for (;iterator.hasNext();){
            Observer os = iterator.next();
            if (os == lane){
                iterator.remove();
                return;
            }
        }
    }
    @Override
    public void publish() {
        laneList.stream().forEach(os->os.receive());
    }

    @Override
    public String getStatus() {
        return lampStatus;
    }

    @Override
    public void setStatus(String status) {
        lampStatus = status;
    }
}
